package cn.nexd.app.collector.adapter;

import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CursorAdapter;
import android.widget.TextView;

import cn.nexd.app.collector.application.NexdApplication;
import cn.nexd.app.collector.presenter.db.NexdSqlOpenHelper;
import cn.nexd.app.collector.presenter.db.TableContract;


/**
 * Created by xun on 2016/8/12.
 */
public class EmailAdapter extends CursorAdapter {
    private LayoutInflater inflater;
    private NexdSqlOpenHelper databaseHelper;
    private SQLiteDatabase db;

    public EmailAdapter(Context context, Cursor c, boolean autoRequery) {
        super(context, c, autoRequery);
        inflater = LayoutInflater.from(context);
        databaseHelper = NexdApplication.getInstance().getSqlHelper();
        db = databaseHelper.getDb();
    }

    @Override
    public View newView(Context context, Cursor cursor, ViewGroup parent) {
        return inflater.inflate(android.R.layout.simple_dropdown_item_1line, parent, false);
    }

    @Override
    public void bindView(View view, Context context, Cursor cursor) {
        if (cursor != null) {
            ((TextView) view).setText(cursor.getString(cursor.getColumnIndex(TableContract.User.COLUMN_NAME_USEREMAIL)));
        }
    }

    @Override
    public CharSequence convertToString(Cursor cursor) {
        return cursor.getString(cursor.getColumnIndex(TableContract.User.COLUMN_NAME_USEREMAIL));
    }

    @Override
    public Cursor runQueryOnBackgroundThread(CharSequence constraint) {
        if (constraint != null) {
            return db.query(TableContract.User.TABLE_NAME, null, TableContract.User.COLUMN_NAME_USEREMAIL + " like \'" + constraint.toString() + "%\'", null, null, null, null);
        } else {
            return null;
        }
    }
}
